const UsersSql = require("../../models/user");
const { hash, compare } = require("../../utils/hash");
const ResHandler = require("../../utils/ResHandler");
const JwtHandler = require('../../utils/jwtHandler');
const resHandler = new ResHandler();
const jwtHandler = new JwtHandler();
const userSql = new UsersSql();
class UserControllers {
  async signin(req, res, next) {
    try {
      const { username, password } = req.body;
      const findRes = await userSql.findUser(username);
      if(findRes) {
        const signRes = await compare(password, findRes.password)
        if(signRes) {
          const token = await jwtHandler.sign(username)
          res.set('X-Access-Token', token)
          res.json(resHandler.succRes({ message: "登录成功" }));
        } else {
          res.json(resHandler.errRes({ message: "登录失败：密码错误或者用户名不存在" }));
        }
      } else {
        res.json(resHandler.errRes({ message: "用户名不存在" }));
      }
    } catch(err) {
      console.log(err);
    }
  }
  async signup(req, res, next) {
    try {
      const { username, password } = req.body;
      const hashPassword = await hash(password);
      const findRes = await userSql.findUser(username);
      if (findRes) {
        res.json(resHandler.errRes({ message: "用户名已存在" }));
      } else {
        const saveRes = await userSql.signup({
          username,
          password: hashPassword,
        });
        if (saveRes) {
          res.json(resHandler.succRes({ message: "注册成功" }));
        }
      }
    } catch (err) {
      next(err);
    }
  }
  async signout(req, res, next) {
    try {
      req.session = null
      res.json(resHandler.succRes({ message: "您已退出登录状态" }));
    } catch(err) {
      console.log(err);
      next(err);
    }
  }
  async isAuth(req, res, next) {
    try {
      res.json(resHandler.succRes({ message: "您已登录", data: true }));
    } catch(err) {
      next(err);
    }
  }
  async deleteUser(req, res, next) {
    try {
      const { id } = req.body;
      const deleteRes = await userSql.deleteUser(id);
      if (deleteRes) {
        res.json(resHandler.succRes({ message: "删除成功" }));
      }
    } catch (err) {
      next(err);
    }
  }
  async getUsers(req, res, next) {
    try {
      const usersList = await userSql.findAllUsers();
      res.json(resHandler.succRes({ data: usersList }));
    } catch (err) {
      next(err);
    }
  }
  async editUser(req, res, next) {
    try {
      const { id, username, password } = req.body;
      const hashPassword = await hash(password);
      const editRes = await userSql.editUser(id, username, hashPassword);
      if (editRes) {
        res.json(resHandler.succRes({ message: "编辑成功" }));
      } else {
        res.json(resHandler.errRes({ message: "编辑失败" }));
      }
    } catch (err) {
      next(err);
    }
  }
}
module.exports = UserControllers;
